package br.com.vestibulation.dao;

import br.com.vestibulation.bean.Opcao;
import br.com.vestibulation.bean.Prova;
import br.com.vestibulation.bean.Questao;
import java.util.ArrayList;

public class ProvaDAO extends ConnectionFactory{

    public Prova getProva(){
        Prova prova = new Prova();
        int maxQuestoes = 10;
        try{
            if(abrir()){
                stmt = conn.prepareStatement("SELECT * FROM questoes ORDER BY random()");
                stmt.setMaxRows(maxQuestoes);
                rs = stmt.executeQuery();
                while(rs.next()){
                    Questao questao = new Questao();
                    questao.setNumero(rs.getInt("idQuestao"));
                    questao.setEnunciado(rs.getString("enunciadoQuestao"));
                    questao.setMateria(rs.getString("materiaQuestao"));
                    prova.getListaQuestoes().add(questao);
                }
                stmt = conn.prepareStatement("SELECT * FROM opcoes WHERE idQuestao = ?");
                for(int i = 0; i<prova.getListaQuestoes().size();i++){
                    ArrayList<Opcao> opcoes = new ArrayList<Opcao>();
                    stmt.setInt(1, prova.getListaQuestoes().get(i).getNumero());
                    rs = stmt.executeQuery();
                    while(rs.next()){
                        Opcao opcao = new Opcao();
                        opcao.setNumero(rs.getInt("idOpcao"));
                        opcao.setOpcao(rs.getString("txtOpcao"));
                        int aux = rs.getInt("certaOpcao");
                        if(aux==0){
                            opcao.setCerta(false);
                        } else{
                            opcao.setCerta(true);
                        }
                        opcoes.add(opcao);
                    }
                    prova.getListaQuestoes().get(i).setListaOpcoes(opcoes);
                }
            }
        } catch(Exception ex){
        } finally{
            fechar();
        }
        return prova;
    }

    public void gerarRelatorio(String usuario, int acertos){
        try{
            if(abrir()){
                stmt = conn.prepareStatement("INSERT INTO relatorio (usuario, dtRealizacao, numAcertos) VALUES (?, CURRENT_DATE, ?)");
                stmt.setString(1, usuario.toLowerCase());
                stmt.setInt(2, acertos);
                stmt.executeUpdate();
            }
        } catch(Exception ex){
        } finally{
            fechar();
        }
    }

}
